#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

void showtid(pthread_t &tid)
{
    printf("tid = 0x%lx\n", tid);
}

std::string FormatId(const pthread_t &tid) // 格式化输出, 是可重入函数
{
    char id[64];
    snprintf(id, sizeof(id), "0x%lx", tid);
    return id;
}

void *routine(void *args)
{
    std::string name = static_cast<const char *>(args);
    pthread_t tid = pthread_self();
    int cnt = 5;
    while (cnt)
    {
        std::cout << "新线程的名字是: " << name << std::endl;
        std::cout << "新线程的ID是: " << FormatId(tid) << std::endl;
        sleep(1);
        cnt--;
    }
    return (void *)123;
}

int main()
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, routine, (void *)"thread-1");
    (void)n;
    showtid(tid);

    int cnt = 5;
    while (cnt)
    {
        std::cout << "主线程的名字是: main thread" << std::endl;
        std::cout << "主线程的ID是: " << FormatId(pthread_self()) << std::endl;
        sleep(1);
        cnt--;
    }
    void *ret = nullptr;
    pthread_join(tid, &ret);
    std::cout << "ret is = " << (long long int)ret << std::endl;
    return 0;
}

#if 0
void *threadrun(void *args)
{
    std::string name = (const char *)args;
    while (true)
    {
        std::cout << "此为新线程: " << name << ", pid: " << getpid() << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, threadrun, (void *)"thread-1");

    while (true)
    {
        std::cout << "我是主线程" << ", pid: " << getpid() << std::endl;
        sleep(1);
    }
    return 0;
}
#endif
